package com.gxa.admin.validator;


import com.gxa.admin.exception.SystemException;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author 蔚枫
 * @version 1.0
 * Talk is cheap. Show me the code
 * @description
 * @date 2021/3/22 13:13
 */
@Component
public class MyValidator {

    /**
     * 验证器
     */
    private Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 不带分组的校验
     *
     * @param obj
     */
    public void validate(Object obj) {
        Set<ConstraintViolation<Object>> validate = validator.validate(obj);
        for (ConstraintViolation<Object> violation : validate) {
            throw new SystemException(1003, violation.getMessage());
        }
    }

    /**
     * 带分组的校验
     *
     * @param obj
     */
    public void validate(Object obj, Class<?> clazz) {
        Set<ConstraintViolation<Object>> validate = validator.validate(obj, clazz);
        /*for (ConstraintViolation<Object> violation : validate) {
            throw new SystemException(1003, violation.getMessage());
        }*/
        StringBuilder msg = new StringBuilder();
        for (ConstraintViolation<Object> violation : validate) {
          msg.append(violation.getMessage());
        }
        // “StringBuffer和StringBuilder”在使用append()方法时，如果append(null)，则它们的“底层源代码”会自动把null转换成字符串的"null"
        if (msg.length()>0 && !"null".equals(msg.toString()) && !"".equals(msg.toString())){
            throw new SystemException(1003, msg.toString());
        }

    }
}
